package com.hifar.test.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hifar.abi.utils.minio.MinioUtils;
import com.hifar.base.serialNo.service.IBaseSerialNoService;
import com.hifar.constant.SystemConsts;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.generate.utils.base.ConstantUtil;
import com.hifar.idm.util.ConvertPdfUtil;
import com.hifar.plat.baseModal.pojo.BaseOssFiles;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.sys.MinioUtil;
import com.hifar.utils.FileUtil;
import com.tssk.kylx.fw.utils.id.IdUtils;
import com.hifar.test.entrust.constant.TaskConsts;
import com.hifar.test.entrust.constant.TestConsts;
import com.hifar.test.entrust.pojo.HfEnvGkEntrust;
import com.hifar.test.entrust.pojo.HfEnvGkPiece;
import com.hifar.test.entrust.service.IHfEnvEntrustService;
import com.hifar.test.entrust.service.IHfEnvGkEntrustService;
import com.hifar.test.entrust.service.IHfEnvGkPieceService;
import com.hifar.test.entrust.service.IHfEnvGkProjectService;
import com.hifar.test.equip.pojo.HfResEquip;
import com.hifar.test.equip.service.IHfResEquipService;
import com.hifar.test.task.mapper.HfEnvTaskMapper;
import com.hifar.test.task.pojo.HfEnvTask;
import com.hifar.test.task.pojo.HfEnvTaskCancel;
import com.hifar.test.task.pojo.VO.*;
import com.hifar.test.task.render.HfEnvTaskOriginalRecordRender;
import com.hifar.test.task.service.IHfEnvTaskCancelService;
import com.hifar.test.task.service.IHfEnvTaskService;
import com.hifar.test.test.pojo.HfEnvTaskTestRelation;
import com.hifar.test.test.pojo.HfEnvTest;
import com.hifar.test.test.pojo.HfEnvTestPiece;
import com.hifar.test.test.pojo.VO.HfEnvEntrustTaskVO;
import com.hifar.test.test.pojo.VO.HfEnvEntrustTestVO;
import com.hifar.test.test.service.IHfEnvTaskTestRelationService;
import com.hifar.test.test.service.IHfEnvTestPieceService;
import com.hifar.test.test.service.IHfEnvTestService;
import com.hifar.test.unit.service.IHfPrjUnitBaseService;
import com.hifar.utils.ToolKit;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 委托项目 服务实现类
 * </p>
 *
 * @author wei
 * @since 2024-12-04 15:51:56
 */
@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class HfEnvTaskServiceImpl extends ServiceImpl<HfEnvTaskMapper, HfEnvTask> implements IHfEnvTaskService {

    @Autowired
    private IHfResEquipService resEquipService;
    @Autowired
    private IBaseSerialNoService baseSerialNoService;
    @Autowired
    private IHfEnvEntrustService entrustService;
    @Autowired
    private IHfEnvGkEntrustService gkEntrustService;
    @Autowired
    private IHfEnvGkPieceService gkPieceService;
    @Autowired
    private IHfEnvGkProjectService gkProjectService;
    @Autowired
    private IHfEnvTestService testService;
    @Autowired
    private IHfPrjUnitBaseService unitBaseService;
    @Autowired
    private IHfEnvTaskTestRelationService taskTestRelationService;
    @Autowired
    private IHfEnvTaskCancelService taskCancelService;
    @Autowired
    private IBaseOssFilesService baseOssFilesService;
    @Autowired
    private IHfEnvTestPieceService testPieceService;
    @Autowired
    private HfEnvTaskOriginalRecordRender taskOriginalRecordRender;


    @Override
    public HfEnvTaskVO queryVoById(String id) {
        HfEnvTask envTask = this.getById(id);
        Assert.notNull(envTask, "数据不存在!");
        HfEnvTaskVO hfEnvTaskVO = new HfEnvTaskVO();
        BeanUtils.copyProperties(envTask, hfEnvTaskVO);
        return hfEnvTaskVO;
    }

    @Override
    public List<HfEnvTask> listByEntrustId(String entrustId) {
        QueryWrapper<HfEnvTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(HfEnvTask::getEntrustId, entrustId)
                .orderByAsc(HfEnvTask::getRowSort);
        return this.list(queryWrapper);
    }

    @Override
    public List<HfEnvTask> listByGkEntrustId(String gkEntrustId) {
        QueryWrapper<HfEnvTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
            .eq(HfEnvTask::getGkEntrustId, gkEntrustId)
            .orderByAsc(HfEnvTask::getRowSort);
        return this.list(queryWrapper);
    }

    @Override
    public void cancel(HfEnvTaskCancelSaveVO taskCancelVO) {
        // 取消任务
        String id = taskCancelVO.getId();
        HfEnvTask hfEnvTask = getById(id);
        Assert.notNull(hfEnvTask, "数据不存在!");
        String status = hfEnvTask.getStatus();
        Assert.isTrue(Objects.equals(TaskConsts.TASK_STATUS_CG, status), "任务已分配，无法取消!");

        List<BaseOssFiles> filesList = Optional.ofNullable(taskCancelVO.getFiles()).orElse(new ArrayList<>());

        UpdateWrapper<HfEnvTask> taskUpdateWrapper = new UpdateWrapper<>();
        taskUpdateWrapper.lambda()
                .set(HfEnvTask::getStatus, TaskConsts.TASK_STATUS_YQX)
                .eq(HfEnvTask::getId, id);
        this.update(taskUpdateWrapper);

        HfEnvTaskCancel hfEnvTaskCancel = new HfEnvTaskCancel();
        BeanUtils.copyProperties(taskCancelVO, hfEnvTaskCancel);
        hfEnvTaskCancel.setTaskId(id);
        hfEnvTaskCancel.setId(null);
        taskCancelService.save(hfEnvTaskCancel);
        String taskCancelId = hfEnvTaskCancel.getId();

        for (BaseOssFiles baseOssFiles : filesList) {
            baseOssFiles.setRefId(taskCancelId);
            baseOssFiles.setRefType(TaskConsts.TASK_CANCEL_FILE_REF_TYPE);
        }
        baseOssFilesService.updateBatchById(filesList);
    }

    @Override
    public void addTest(AddTestVO addTestVO) {
        List<String> taskIdList = addTestVO.getTaskIdList();
//        BigDecimal predictUseTime = addTestVO.getPredictUseTime();
        Date predictStartTime = addTestVO.getPredictStartTime();
        Date predictEndTime = addTestVO.getPredictEndTime();
        String equipId = addTestVO.getEquipId();
        Integer secretLevel = addTestVO.getSecretLevel();
        String testCode = baseSerialNoService.getMouthSerialNo(TestConsts.NO_TYPE, "yyyyMMdd", "SX", "", 2);
        HfResEquip hfResEquip = resEquipService.getById(equipId);
        Assert.notNull(hfResEquip, "设备数据不存在!");

        Long predictUseTime = ToolKit.diffTime(predictStartTime, predictEndTime);
        List<HfEnvTask> taskList = this.listByIds(taskIdList);

        Set<String> unitIdSet = taskList.stream()
                .map(HfEnvTask::getUnitId)
                .collect(Collectors.toSet());
        Assert.isTrue(unitIdSet.size() == 1, "试验项目不同不能合并分配!");
        HfEnvTask firstTask = taskList.get(0);

        String unitId = firstTask.getUnitId();
        String unitCode = firstTask.getUnitCode();
        String unitName = firstTask.getUnitName();

        Assert.notEmpty(taskList, "任务数据不存在!");
        HfEnvTest hfEnvTest = new HfEnvTest();
        hfEnvTest.setEquipId(equipId);
        hfEnvTest.setEquipCode(hfResEquip.getEquipCode());
        hfEnvTest.setEquipModel(hfResEquip.getEquipModel());
        hfEnvTest.setEquipName(hfResEquip.getEquipName());
        hfEnvTest.setInnerName(hfResEquip.getInnerName());
        hfEnvTest.setCheckValid(hfResEquip.getCheckValid());
        hfEnvTest.setPredictEndTime(predictEndTime);
        hfEnvTest.setPredictStartTime(predictStartTime);
        hfEnvTest.setStatus(TestConsts.TEST_STATUS_WKS);
        hfEnvTest.setIzSaveData(SystemConsts.NO);
        hfEnvTest.setIzOriginalRecord(SystemConsts.NO);

        hfEnvTest.setUnitCode(unitCode);
        hfEnvTest.setUnitName(unitName);
        hfEnvTest.setUnitId(unitId);

        hfEnvTest.setPredictUseTime(predictUseTime);
        hfEnvTest.setTestCode(testCode);
        hfEnvTest.setSecretLevel(secretLevel);
        testService.save(hfEnvTest);
        String testId = hfEnvTest.getId();
        List<HfEnvTaskTestRelation> taskTestRelationList = new ArrayList<>();

        int testPieceRowSort = 1;
        List<HfEnvTestPiece> testPieceList = new ArrayList<>();
        for (HfEnvTask hfEnvTask : taskList) {
            String gkEntrustId = hfEnvTask.getGkEntrustId();
            String taskId = hfEnvTask.getId();
            HfEnvTaskTestRelation hfEnvTaskTestRelation = new HfEnvTaskTestRelation();
            hfEnvTaskTestRelation.setTestId(testId);
            hfEnvTaskTestRelation.setTaskId(taskId);
            hfEnvTaskTestRelation.setGkEntrustId(gkEntrustId);
            taskTestRelationList.add(hfEnvTaskTestRelation);

            List<HfEnvGkPiece> gkPieceList = gkPieceService.listByGkEntrustId(gkEntrustId);

            for (HfEnvGkPiece gkPiece : gkPieceList) {
                HfEnvTestPiece hfEnvTestPiece = new HfEnvTestPiece();
                hfEnvTestPiece.setTestId(testId);
                hfEnvTestPiece.setPieceNo(gkPiece.getPieceNo());
                hfEnvTestPiece.setPieceId(gkPiece.getId());
                hfEnvTestPiece.setProductAlias(gkPiece.getProductAlias());
                hfEnvTestPiece.setProductCode(gkPiece.getProductCode());
                hfEnvTestPiece.setProductName(gkPiece.getProductName());
                hfEnvTestPiece.setRowSort(testPieceRowSort++);
                testPieceList.add(hfEnvTestPiece);
            }
        }
        testPieceService.saveBatch(testPieceList);
        taskTestRelationService.saveBatch(taskTestRelationList);
        this.refreshTaskStatus(testId);

    }

    @Override
    public TaskMatchAndNumDTO taskMatchEquipList(TaskMatchEquipQueryVO matchEquipQueryVO) {

        Date startTime = matchEquipQueryVO.getStartTime();
        Date endTime = matchEquipQueryVO.getEndTime();

        List<String> taskIdList = matchEquipQueryVO.getTaskIdList();
        List<HfEnvTask> taskList = this.listByIds(taskIdList);
        Assert.notEmpty(taskList, "任务数据不存在!");
        List<TaskMatchEquipVO> taskMatchEquipList = resEquipService.matchEquipList();
        if (taskMatchEquipList.isEmpty()) {
            return new TaskMatchAndNumDTO();
        }
        List<String> equipIdList = taskMatchEquipList.stream()
                .map(TaskMatchEquipVO::getId)
                .collect(Collectors.toList());
        List<EquipTestInfoVO> allTestInfoVOList = testService.listRunTest(equipIdList, startTime, endTime);

        Map<String, Integer> typeFlagNumMap = allTestInfoVOList.stream()
                .collect(Collectors.toMap(
                        EquipTestInfoVO::getTypeFlag,
                        item -> 1,
                        Integer::sum
                ));


        Map<String, List<EquipTestInfoVO>> testEquipGroup = allTestInfoVOList.stream()
                .collect(Collectors.groupingBy(EquipTestInfoVO::getEquipId));

        for (TaskMatchEquipVO taskMatchEquipVO : taskMatchEquipList) {
            String id = taskMatchEquipVO.getId();
            List<EquipTestInfoVO> equipTestInfoList = testEquipGroup.getOrDefault(id, new ArrayList<>());

            Date checkValid = taskMatchEquipVO.getCheckValid();
            String validFlag = SystemConsts.NO;
            if (Objects.nonNull(checkValid)) {
                validFlag = new Date().after(checkValid) ? SystemConsts.YES : SystemConsts.NO;
            }
            taskMatchEquipVO.setValidFlag(validFlag);

            taskMatchEquipVO.setEquipTestInfo(equipTestInfoList);
        }

        TestStatusNumVO testStatusNumVO = new TestStatusNumVO();

        // 初始化所有统计字段为0
        testStatusNumVO.setNotStartNum(0);
        testStatusNumVO.setRunningNum(0);
        testStatusNumVO.setTimeOutNum(0);

        typeFlagNumMap.forEach((k, v) -> {
            switch (k) {
                case TestConsts.TYPE_FLAG_NOT_START:
                    testStatusNumVO.setNotStartNum(v);
                    break;
                case TestConsts.TYPE_FLAG_RUNNING:
                    testStatusNumVO.setRunningNum(v);
                    break;
                case TestConsts.TYPE_FLAG_TIMEOUT:
                    testStatusNumVO.setTimeOutNum(v);
                    break;
                default:
                    break;
            }
        });

        // 计算最大显示结束时间和最小显示开始时间
        if (!allTestInfoVOList.isEmpty()) {
            Date maxShowEndTime = allTestInfoVOList.stream()
                    .map(EquipTestInfoVO::getShowEndTime)
                    .filter(Objects::nonNull)
                    .max(Date::compareTo)
                    .orElse(null);

            Date minShowStartTime = allTestInfoVOList.stream()
                    .map(EquipTestInfoVO::getShowStartTime)
                    .filter(Objects::nonNull)
                    .min(Date::compareTo)
                    .orElse(null);

            testStatusNumVO.setMaxShowEndTime(maxShowEndTime);
            testStatusNumVO.setMinShowStartTime(minShowStartTime);
        }

        TaskMatchAndNumDTO taskMatchAndNumDTO = new TaskMatchAndNumDTO();
        taskMatchAndNumDTO.setTaskMatchEquipVOList(taskMatchEquipList);
        taskMatchAndNumDTO.setNumVO(testStatusNumVO);
        return taskMatchAndNumDTO;
    }


    @Override
    public List<TaskPendingEntrustVO> listPendingEntrust(QueryWrapper<HfEnvGkEntrust> queryWrapper) {

        queryWrapper.apply(" exists (select 1 from hf_env_task t " +
                        "              where t.gk_entrust_id=e.id and t.status  in ({0},{1},{2}))",
                TaskConsts.TASK_STATUS_CG, TaskConsts.TASK_STATUS_EXECUTED,TaskConsts.TASK_STATUS_YFP);
        queryWrapper.eq("e.del_flag", "0");

        queryWrapper.orderByDesc("e.create_time");
        List<TaskPendingEntrustVO> taskPendingEntrustList = baseMapper.selectPendingEntrust(queryWrapper);

        if (taskPendingEntrustList.isEmpty()) {
            return new ArrayList<>();
        }

        Set<String> gkEntrustIdSet = taskPendingEntrustList.stream()
                .map(TaskPendingEntrustVO::getId)
                .collect(Collectors.toSet());
        QueryWrapper<HfEnvTask> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.lambda()
                .select(HfEnvTask::getId, HfEnvTask::getGkEntrustId)
                .eq(HfEnvTask::getStatus, TaskConsts.TASK_STATUS_CG)
                .in(HfEnvTask::getGkEntrustId, gkEntrustIdSet);
        List<HfEnvTask> taskList = this.list(taskQueryWrapper);
        Map<String, Integer> entrustTaskNumMap = taskList.stream()
                .collect(Collectors.toMap(
                        HfEnvTask::getGkEntrustId,
                        item -> 1,
                        Integer::sum
                ));
        for (TaskPendingEntrustVO taskPendingEntrustVO : taskPendingEntrustList) {
            String id = taskPendingEntrustVO.getId();
            Integer notAllocatedNum = entrustTaskNumMap.getOrDefault(id, 0);
            taskPendingEntrustVO.setNotAllocatedNum(notAllocatedNum);
        }
        return taskPendingEntrustList;
    }

    @Override
    public Page<HfEnvTaskVO> pageVO(Page<HfEnvTask> page, QueryWrapper<HfEnvTask> queryWrapper) {
        Page<HfEnvTaskVO> voPage = baseMapper.selectVOPage(page, queryWrapper);
        List<HfEnvTaskVO> records = voPage.getRecords();
        if (records.isEmpty()) {
            return voPage;
        }
        Set<String> taskIdSet = records.stream()
                .map(HfEnvTaskVO::getId)
                .collect(Collectors.toSet());
        QueryWrapper<HfEnvTaskTestRelation> taskTestRelationQueryWrapper = new QueryWrapper<>();
        taskTestRelationQueryWrapper.lambda()
                .in(HfEnvTaskTestRelation::getTaskId, taskIdSet)
                .apply(" exists (select 1 from hf_env_test t " +
                                " where t.id=test_id and t.status !={0} )"
                        , TestConsts.TEST_STATUS_REVOKE);
        List<HfEnvTaskTestRelation> taskTestRelationList = taskTestRelationService.list(taskTestRelationQueryWrapper);
        Map<String, Integer> taskTestNumMap = taskTestRelationList.stream()
                .collect(Collectors.toMap(
                        HfEnvTaskTestRelation::getTaskId,
                        item -> 1,
                        Integer::sum
                ));
        List<HfEnvTaskTestRelation> notStopTaskTestRelationList = taskTestRelationService.lambdaQuery()
                .in(HfEnvTaskTestRelation::getTaskId, taskIdSet)
                .apply(" exists (select 1 from hf_env_test t " +
                                " where t.id=test_id and t.status not in ({0},{1}) )"
                        , TestConsts.TEST_STATUS_REVOKE, TestConsts.TEST_STATUS_STOP)
                .list();
        Map<String, Integer> notStopTaskTestNumMap = notStopTaskTestRelationList.stream()
                .collect(Collectors.toMap(
                        HfEnvTaskTestRelation::getTaskId,
                        item -> 1,
                        Integer::sum
                ));


        for (HfEnvTaskVO record : records) {
            String id = record.getId();
            String status = record.getStatus();
            Integer testNum = taskTestNumMap.getOrDefault(id, 0);
            Integer notTestNum = notStopTaskTestNumMap.getOrDefault(id, 0);
            record.setTestNum(testNum);
            Integer secretLevel = record.getSecretLevel();
            //  或者其底下的所有试验都是已终止时才可点击
            record.setIsCatItCancel(Objects.equals(TaskConsts.TASK_STATUS_CG, status) && notTestNum <= 0);
            String pdfPathXh = record.getPdfPathXh();
            String docxPathXh = record.getDocxPathXh();
            if (StringUtils.isNotBlank(pdfPathXh)) {
                record.setPdfPathXh(MinioUtil.getFullFilePaths(MinioUtil.PRE_DEFAULT, pdfPathXh, secretLevel));
            }
            if (StringUtils.isNotBlank(docxPathXh)) {
                record.setDocxPathXh(MinioUtil.getFullFilePaths(MinioUtil.PRE_DEFAULT, docxPathXh, secretLevel));
            }

        }
        return voPage;
    }

    @Override
    public Page<HfEnvTaskTestVO> pageTest(Page<HfEnvTest> page, QueryWrapper<HfEnvTest> queryWrapper) {
        return baseMapper.pageTest(page, queryWrapper);
    }

    @Override
    public void refreshTaskStatus(String testId) {
        HfEnvTest envTest = testService.getById(testId);
        Assert.notNull(envTest, "试验数据不存在!");

        List<HfEnvTaskTestRelation> taskTestRelationList = taskTestRelationService.lambdaQuery()
                .eq(HfEnvTaskTestRelation::getTestId, testId).list();
        Assert.notEmpty(taskTestRelationList, "数据不存在!");
        List<String> taskIdList = taskTestRelationList.stream()
                .map(HfEnvTaskTestRelation::getTaskId)
                .collect(Collectors.toList());
        List<HfEnvTask> taskList = this.listByIds(taskIdList);
        for (HfEnvTask hfEnvTask : taskList) {
            String gkEntrustId = hfEnvTask.getGkEntrustId();
            String taskStatus = hfEnvTask.getStatus();
            String taskId = hfEnvTask.getId();
            if (Objects.equals(TaskConsts.TASK_STATUS_FORCE_END, taskStatus)) {
                continue;
            }
            List<HfEnvTaskTestRelation> taskTestList = taskTestRelationService.lambdaQuery()
                    .eq(HfEnvTaskTestRelation::getTaskId, taskId)
                    .list();
            List<String> taskTestIdList = taskTestList.stream()
                    .map(HfEnvTaskTestRelation::getTestId)
                    .collect(Collectors.toList());
            List<HfEnvTest> testList = testService.listByIds(taskTestIdList);
            List<String> testStatusList = testList.stream()
                    .map(HfEnvTest::getStatus)
                    .distinct()
                    .collect(Collectors.toList());
            if (testStatusList.isEmpty()) {
                taskStatus = TaskConsts.TASK_STATUS_CG;
            } else {
                // 已完成 所有状态都为已完成或已终止 且至少包含一个已完成
                boolean isFinish = Arrays.asList(TestConsts.TEST_STATUS_FINISH
                        , TestConsts.TEST_STATUS_STOP
                        , TestConsts.TEST_STATUS_REVOKE).containsAll(testStatusList)
                        && testStatusList.contains(TestConsts.TEST_STATUS_FINISH);
                // 已分配：该任务单下至少有1个试验，且所有的试验均是未开始状态。
//                boolean isAllocation = testStatusList.stream()
//                        .filter(item -> !Objects.equals(TestConsts.TEST_STATUS_REVOKE, item))
//                        .allMatch(item -> Objects.equals(TestConsts.TEST_STATUS_WKS, item));
                boolean isAllocation = testStatusList.stream()
                        .filter(item -> !Objects.equals(TestConsts.TEST_STATUS_REVOKE, item))
                        .collect(Collectors.toList()).containsAll(Arrays.asList(TestConsts.TEST_STATUS_WKS));
                if (isFinish) {
                    taskStatus = TaskConsts.TASK_STATUS_FINISH;
                } else if (isAllocation) {
                    taskStatus = TaskConsts.TASK_STATUS_YFP;
                } else {
                    // 试验全为未开始或已撤销
                    boolean isNotStart = Arrays.asList(TestConsts.TEST_STATUS_WKS, TestConsts.TEST_STATUS_REVOKE).containsAll(testStatusList);
                    taskStatus = isNotStart ? TaskConsts.TASK_STATUS_CG : TaskConsts.TASK_STATUS_EXECUTED;
                }
            }
            this.lambdaUpdate()
                    .set(HfEnvTask::getStatus, taskStatus)
                    .eq(HfEnvTask::getId, taskId)
                    .update();
            gkEntrustService.refreshEntrustStatus(taskId);
        }
    }

    @Override
    public void updateEntrustId(String gkEntrustId, String entrustId) {
        this.lambdaUpdate()
                .set(HfEnvTask::getEntrustId, entrustId)
                .eq(HfEnvTask::getGkEntrustId, gkEntrustId)
                .update();
    }

    @Override
    public List<HfEnvTask> reportListTaskByEntrustId(String entrustId) {
        return baseMapper.reportListTaskByEntrustId(entrustId);
    }


    @Override
    public List<HfEnvTask> reportListTaskByGkEntrustId(String gkEntrustId) {
        return baseMapper.reportListTaskByGkEntrustId(gkEntrustId);
    }

    @Override
    public TaskMatchAndNumDTO equipTestBoardList(EquipTestBoardQueryVO equipTestBoardQueryVO) {
        Date startTime = equipTestBoardQueryVO.getStartTime();
        Date endTime = equipTestBoardQueryVO.getEndTime();
        TaskMatchAndNumDTO taskMatchAndNumDTO = new TaskMatchAndNumDTO();



        List<TaskMatchEquipVO> taskMatchEquipList = resEquipService.matchEquipList();
        if (taskMatchEquipList.isEmpty()) {
            return taskMatchAndNumDTO;
        }
        List<String> equipIdList = taskMatchEquipList.stream()
                .map(TaskMatchEquipVO::getId)
                .collect(Collectors.toList());
        List<EquipTestInfoVO> allTestInfoVOList = testService.listRunTest(equipIdList, startTime, endTime);
        Map<String, List<EquipTestInfoVO>> testEquipGroup = allTestInfoVOList.stream()
                .collect(Collectors.groupingBy(EquipTestInfoVO::getEquipId));


        Map<String, Integer> typeFlagNumMap = allTestInfoVOList.stream()
                .collect(Collectors.toMap(
                        EquipTestInfoVO::getTypeFlag,
                        item -> 1,
                        Integer::sum
                ));

        for (TaskMatchEquipVO taskMatchEquipVO : taskMatchEquipList) {
            String id = taskMatchEquipVO.getId();
            List<EquipTestInfoVO> equipTestInfoList = testEquipGroup.getOrDefault(id, new ArrayList<>());
            taskMatchEquipVO.setEquipTestInfo(equipTestInfoList);
        }
        TestStatusNumVO testStatusNumVO = new TestStatusNumVO();

        // 初始化所有统计字段为0
        testStatusNumVO.setNotStartNum(0);
        testStatusNumVO.setRunningNum(0);
        testStatusNumVO.setTimeOutNum(0);

        typeFlagNumMap.forEach((k, v) -> {
            switch (k) {
                case TestConsts.TYPE_FLAG_NOT_START:
                    testStatusNumVO.setNotStartNum(v);
                    break;
                case TestConsts.TYPE_FLAG_RUNNING:
                    testStatusNumVO.setRunningNum(v);
                    break;
                case TestConsts.TYPE_FLAG_TIMEOUT:
                    testStatusNumVO.setTimeOutNum(v);
                    break;
                default:
                    break;
            }
        });

        // 计算最大显示结束时间和最小显示开始时间
        if (!allTestInfoVOList.isEmpty()) {
            Date maxShowEndTime = allTestInfoVOList.stream()
                    .map(EquipTestInfoVO::getShowEndTime)
                    .filter(Objects::nonNull)
                    .max(Date::compareTo)
                    .orElse(null);

            Date minShowStartTime = allTestInfoVOList.stream()
                    .map(EquipTestInfoVO::getShowStartTime)
                    .filter(Objects::nonNull)
                    .min(Date::compareTo)
                    .orElse(null);

            testStatusNumVO.setMaxShowEndTime(maxShowEndTime);
            testStatusNumVO.setMinShowStartTime(minShowStartTime);
        }

        taskMatchAndNumDTO.setTaskMatchEquipVOList(taskMatchEquipList);
        taskMatchAndNumDTO.setNumVO(testStatusNumVO);

        return taskMatchAndNumDTO;
    }

    @Override
    public HfEnvTaskCancelVO queryCancelById(String id) {
        HfEnvTaskCancel hfEnvTaskCancel = taskCancelService.lambdaQuery()
                .eq(HfEnvTaskCancel::getTaskId, id)
                .orderByDesc(HfEnvTaskCancel::getCreateTime)
                .one();
        Assert.notNull(hfEnvTaskCancel, "任务取消数据不存在!");

        HfEnvTaskCancelVO taskCancelVO = new HfEnvTaskCancelVO();
        BeanUtils.copyProperties(hfEnvTaskCancel, taskCancelVO);

        List<BaseOssFiles> filesList = MinioUtil.listByRefId(hfEnvTaskCancel.getId(), TaskConsts.TASK_CANCEL_FILE_REF_TYPE);
        taskCancelVO.setFiles(filesList);
        return taskCancelVO;
    }


    @Override
    public List<HfEnvEntrustTaskVO> listVoByEntrustId(String entrustId) {
        List<HfEnvTask> taskList = this.lambdaQuery()
                .eq(HfEnvTask::getEntrustId, entrustId)
                .orderByAsc(HfEnvTask::getRowSort)
                .list();
        List<HfEnvEntrustTaskVO> taskVOList = new ArrayList<>(taskList.size());
        for (HfEnvTask hfEnvTask : taskList) {
            String taskId = hfEnvTask.getId();
            HfEnvEntrustTaskVO hfEnvEntrustTaskVO = new HfEnvEntrustTaskVO();
            BeanUtils.copyProperties(hfEnvTask, hfEnvEntrustTaskVO);
            List<HfEnvEntrustTestVO> testVOList = testService.testListByTaskId(taskId);
            hfEnvEntrustTaskVO.setTestList(testVOList);
            taskVOList.add(hfEnvEntrustTaskVO);
        }
        return taskVOList;
    }


    @Override
    public void deleteById(String id) {
        HfEnvTask hfEnvTask = this.getById(id);
        Assert.notNull(hfEnvTask, "数据不存在!");
        String status = hfEnvTask.getStatus();
        Assert.isTrue(Arrays.asList(TaskConsts.TASK_STATUS_CG, TaskConsts.TASK_STATUS_YQX).contains(status), "当前状态无法删除!");
        String gkEntrustId = hfEnvTask.getGkEntrustId();
        this.removeById(id);
        List<HfEnvTask> taskList = this.listTaskByGkEntrustId(gkEntrustId);
        if (taskList.isEmpty()) {
            gkEntrustService.removeById(gkEntrustId);
            gkPieceService.removeByGkEntrustId(gkEntrustId);
            gkProjectService.removeById(gkEntrustId);
        }
    }

    @Override
    public List<HfEnvTask> listTaskByGkEntrustId(String gkEntrustId) {
        return this.lambdaQuery()
                .eq(HfEnvTask::getGkEntrustId, gkEntrustId)
                .orderByAsc(HfEnvTask::getRowSort)
                .list();
    }


    @Override
    public void removeByGkEntrustId(String gkEntrustId) {
        QueryWrapper<HfEnvTask> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.lambda()
                .eq(HfEnvTask::getGkEntrustId, gkEntrustId);
        this.remove(taskQueryWrapper);
    }

    @Override
    public void generateProcessRecord(String id) {
        taskOriginalRecordRender.renderReport(id);
    }

    @Override
    public void replaceTestReport(String id, String fileId) {
        BaseOssFiles baseOssFile = baseOssFilesService.getById(fileId);
        Assert.notNull(baseOssFile, "附件不存在!");
        HfEnvTask hfEnvTask = this.getById(id);
        Assert.notNull(hfEnvTask, "任务数据不存在!");

        String wordFilePath = baseOssFile.getFilePath();
        String bucketPre = baseOssFile.getBucketPre();
        String tempWordPath = FileUtil.getTempPath() + File.separator + IdUtils.uuid32() + ".docx";

        String docxObjectName = "hifar/idm/task/" + id + "Original.docx";
        String pdfObjectName = "hifar/idm/task/" + id + "Original.pdf";

        String pdfPath = null;
        try {
            MinioUtils.downloadFileToLocal(bucketPre, wordFilePath, tempWordPath);
            MinioUtils.uploadFileToMinioByStream(ConstantUtil.MINIO_BUCKET_PUBLIC, docxObjectName, new File(tempWordPath));
            pdfPath = ConvertPdfUtil.wordToPdf(tempWordPath);
            MinioUtils.uploadLocalFileToMinio(ConstantUtil.MINIO_BUCKET_PUBLIC, pdfObjectName, pdfPath, "application/pdf");
            UpdateWrapper<HfEnvTask> taskUpdateWrapper = new UpdateWrapper<>();
            taskUpdateWrapper.lambda()
                    .set(HfEnvTask::getDocxPathXh, docxObjectName)
                    .set(HfEnvTask::getPdfPathXh, pdfObjectName)
                    .eq(HfEnvTask::getId, id);
            this.update(taskUpdateWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            File tempWordFile = new File(tempWordPath);
            if (tempWordFile.exists()) {
                tempWordFile.delete();
            }
            if (Objects.nonNull(pdfPath)) {
                File tempPdfFile = new File(pdfPath);
                if (tempPdfFile.exists()) {
                    tempPdfFile.delete();
                }
            }
        }
    }

    @Override
    public void delTestReport(String id) {
        HfEnvTask hfEnvTask = this.getById(id);
        Assert.notNull(hfEnvTask, "任务数据不存在!");
        UpdateWrapper<HfEnvTask> taskUpdateWrapper = new UpdateWrapper<>();
        taskUpdateWrapper.lambda()
                .set(HfEnvTask::getPdfPathXh, null)
                .set(HfEnvTask::getDocxPathXh, null)
                .eq(HfEnvTask::getId, id);
        this.update(taskUpdateWrapper);
    }
}
